import React, { useCallback, useState } from 'react';
import { useAntdTable } from 'ahooks';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  DatePicker,
  Form,
  Input,
  Row,
  Select,
  Space,
  Table,
  Pagination,
  Cascader,
  message,
  Modal,
} from 'antd';
import usePermissionCheck from '@/hooks/usePermissionCheck';
import { fetchUndefinedData, stopTask } from '@/services/userFeedback/logRetrieval';
import useOptions from '../hooks/useOptions';
import AddTaskModal from './addTaskModal';
import DetailModal from './detailModal';

const status = ['进行中', '完成', '失败', '终止', '超时'];

const undefinedPane: React.FC<any> = ({ permissions }) => {
  const [isAdd] = usePermissionCheck(permissions, 'logRetrieval-add-task');
  const [form] = Form.useForm();
  const [id, setId] = useState<null | string>(null);
  const [open, setOpen] = useState(false);
  const { brand, series, version, onChange, filter } = useOptions(form);

  const fetchData = useCallback(async ({ current, pageSize }: any, formData: any) => {
    if (formData.vehicleType && Array.isArray(formData.vehicleType)) {
      const [_, vehicleType] = formData.vehicleType;
      formData.vehicleType = vehicleType;
    }

    const result = await fetchUndefinedData({ size: pageSize, page: current, ...formData });
    return {
      list: result?.list || [],
      total: result?.pagination.total || 0,
    };
  }, []);

  const { search, tableProps, pagination, refresh } = useAntdTable(fetchData, {
    form,
  });
  const { submit, reset } = search;

  const handleSubmit = () => {
    reset();
  };

  const handleStop = (id: string) => {
    Modal.confirm({
      title: '确定终止该任务吗?',
      onOk() {
        stopTask(id).then(() => {
          message.success('终止成功');
          refresh();
        });
      },
    });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      render: (text: any, record: any, index: any) => {
        return index + 1 + (pagination.current - 1) * pagination.pageSize;
      },
    },
    {
      title: '关键字',
      dataIndex: 'keyWord',
    },
    {
      title: 'VIN',
      dataIndex: 'vin',
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
    },
    {
      title: '车型',
      dataIndex: 'vehicleType',
    },
    {
      title: '版本',
      dataIndex: 'version',
    },
    {
      title: '上传日期',
      dataIndex: 'uploadDate',
      render: (text: string) => text?.replace(/-/, '~')?.replace(/:/g, '-'),
    },
    {
      title: '发起时间',
      dataIndex: 'createTime',
    },
    {
      title: '日志类型',
      dataIndex: 'logType',
      render: (text: number) => ['全部', '异常日志', '全量日志'][text],
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text: number) => status[text],
    },
    {
      title: '文档数',
      dataIndex: 'documentNum',
      render: (text: number, row: { status: number; }) => row.status === 1 ? text : '-',
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 60,
      render: (id: string, _: any) =>
        _.status ? (
          <Button type="link" onClick={() => setId(id)} disabled={_.status !== 1}>详情</Button>
        ) : (
          <Button type="link" onClick={() => handleStop(id)}>终止</Button>
        ),
    },
  ];
  return (
    <div>
      {isAdd && (
        <Button
          type="primary"
          onClick={() => setOpen(true)}
          style={{ position: 'absolute', top: 16, right: 16 }}
        >
          创建任务
        </Button>
      )}
      <Form form={form} layout="inline">
        <Row wrap style={{ width: '100%', gap: 12 }}>
          <Form.Item label="关键字" name="keyWord">
            <Input placeholder="请输入关键字" allowClear />
          </Form.Item>
          <Form.Item label="VIN码" name="vin">
            <Input maxLength={17} placeholder="请输入VIN码" allowClear style={{ width: 162 }} />
          </Form.Item>
          <Form.Item label="版本" name="version">
            <Select showSearch allowClear placeholder="请选择版本" style={{ width: 162 }}>
              {version?.map((item: any) => (
                <Select.Option key={item} value={item}>
                  {item}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="日志类型" name="logType">
            <Select showSearch allowClear placeholder="请选择日志类型" style={{ width: 162 }}>
              {['异常日志', '全量日志']?.map((item: string, index) => (
                <Select.Option key={item} value={index + 1}>
                  {item}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="品牌" name="brandCode">
            <Select
              onChange={onChange}
              showSearch
              allowClear
              placeholder="请选择品牌"
              style={{ width: 162 }}
            >
              {brand?.map((item: any) => (
                <Select.Option key={item.brandCode} value={item.brandCode}>
                  {item.brandName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="车型" name="vehicleType">
            <Cascader
              showSearch={{ filter }}
              options={series}
              style={{ minWidth: 182 }}
              placeholder="请选择车型"
            />
          </Form.Item>
          <Form.Item label="上传日期" name="rangeTime">
            <DatePicker.RangePicker
              format="YYYY-MM-DD"
              disabledDate={current =>
                current && (current < moment().subtract(30, 'days') || current > moment())
              }
            />
          </Form.Item>
          <Form.Item label="发起时间" name="createTime">
            <DatePicker.RangePicker
              format="YYYY-MM-DD"
              disabledDate={current =>
                current && (current < moment().subtract(30, 'days') || current > moment())
              }
            />
          </Form.Item>
          <Space size={12} style={{ marginLeft: 'auto' }}>
            <Button type="primary" onClick={submit} htmlType="submit">
              查询
            </Button>
            <Button htmlType="button" onClick={reset}>
              重置
            </Button>
          </Space>
        </Row>
      </Form>
      <Table
        style={{ marginTop: 12 }}
        size={'small'}
        rowKey="id"
        columns={columns}
        scroll={{ x: 'max-content' }}
        {...tableProps}
        pagination={false}
      />
      <Row justify="end" style={{ padding: '12px 0' }}>
        <Pagination
          // hideOnSinglePage
          showSizeChanger
          size="small"
          showQuickJumper
          {...pagination}
          showTotal={() => <span>共&nbsp;{pagination.total}&nbsp;条</span>}
          pageSizeOptions={['10', '20', '50', '100']}
        />
      </Row>

      <AddTaskModal open={open} onSubmit={handleSubmit} onCancel={() => setOpen(false)} />
      {id && <DetailModal id={id} onCancel={() => setId(null)} />}
    </div>
  );
};

export default connect(({ menu }: any) => ({ permissions: menu.permissions }))(undefinedPane);
